//
// Created by par on 2022/11/14.
//
#include <fmt/core.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string>
#include <filesystem>

#include "arg.hpp"
#include "sock.hpp"

using namespace std;
namespace fs = filesystem;

int init_cli(ClientArgs &args) {
    auto sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        fmt::print("create socket fail\n");
        exit(-1);
    }

    sockaddr_in serv_addr = {};
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(args.port);
    inet_aton(args.server.c_str(), &serv_addr.sin_addr);

    auto rv = connect(sockfd, reinterpret_cast<const sockaddr *>(&serv_addr), sizeof(serv_addr));
    if (rv < 0) {
        fmt::print("fail to connect to {}:{}\n", inet_ntoa(serv_addr.sin_addr), ntohs(serv_addr.sin_port));
        exit(-2);
    }
//    fmt::print("connect to {}:{}\n", inet_ntoa(serv_addr.sin_addr), ntohs(serv_addr.sin_port));

    return sockfd;
}

int main(int argc, char *argv[]) {
    auto args = parse_cli_args(argc, argv);

    fmt::print("list: {}, server: {}, port: {}, dl: {}, output: {}\n",
               args.list, args.server, args.port, args.dl, args.output);

    auto sockfd = init_cli(args);

    if (args.list) {
        sendStr(sockfd, "list");
        fmt::print("{}", recvStr(sockfd));
    } else {
        if (fs::exists(args.output)) {
            fmt::print("failed to download {}: {} already exists", args.output, args.output);
            exit(EXIT_FAILURE);
        }
        sendStr(sockfd, "dl");
        sendStr(sockfd, args.dl);
        // todo 区分传送名字、下载名字
        recvFile(sockfd, args.output.empty() ? args.dl : args.output);
    }

    close(sockfd);

    return 0;
}